import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt

## 生产一些示例数据
x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.18],
            [9.779], [6.182], [7.59], [2.167], [7.042],
            [10.791], [5.313],  [7.997], [3.1]], dtype=np.float32)

y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573]
                    , [3.366], [2.596], [2.53], [1.221], [2.827]
                    , [3.465], [1.65], [2.904], [1.3]], dtype=np.float32)

# 将numpy 数组转换为 PyTorch 张量
x_train = torch.from_numpy(x_train)
y_train = torch.from_numpy(y_train)

# 定义线性回归模型
class LinearRegression(nn.Module):
    def __init__(self):
        super(LinearRegression, self).__init__()
        self.linear = nn.Linear(1, 1) # 输入维度为 1， 输出维度为 1
    def forward(self, x):
        out = self.linear(x)
        return out
model = LinearRegression()

# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

# 训练模型
num_epochs = 1000

for epoch in range(num_epochs):
    # 前向传播
    outputs = model(x_train)
    loss = criterion(outputs, y_train)
    # 反向传播和优化
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    if (epoch+1) % 100 == 0:
        print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item(): .4f}')
# 绘制结果
predicted = model(x_train).detach().numpy()
plt.plot(x_train.numpy(), y_train.numpy(), 'ro', label='Original data')
plt.plot(x_train.numpy(), predicted, label='Fitted line')
plt.legend()
plt.show()
